document.querySelectorAll(".images-difference").forEach(elem => {
    const inReverse = elem.classList.contains("reverse");

    const curtain = elem.querySelector('.curtain');

    const imagesContainer = elem.querySelector(".images-container");

    const firstImage = imagesContainer.querySelector('.difference-image.first');
    const secondImage = imagesContainer.querySelector('.difference-image.second');


    if (inReverse) {
        elem.addEventListener("mouseenter", function (event) {
            swapImages(secondImage);
        });
    }

    imagesContainer.addEventListener("mousemove", function (event) {
        const offsetX = event.offsetX;

        if (inReverse) {
            firstImage.style.width = offsetX + "px";
        } else {
            secondImage.style.width = offsetX + "px";
        }

        curtain.style.display = "block";
        curtain.style.transform = `translateX(${offsetX - (curtain.scrollWidth / 2)}px)`
    });

    elem.addEventListener("mouseleave", function (event) {
        if (inReverse) {
            swapImages(firstImage)
            firstImage.style.removeProperty('width');
        } else {
            secondImage.style.removeProperty('width');
        }

        curtain.style.removeProperty('display');
        curtain.style.removeProperty('translateX');
    });
})

function swapImages(image) {
    const parent = image.parentNode;
    const prev = image.previousElementSibling;

    parent.insertBefore(image, prev);
}